/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package SessionBeans.actions;

import SessionBeans.entites.FolderService;
import api.action.crates.Server.NewFolderCrate;
import api.exception.TCloudAplicationException;
import api.exception.TCloudAplicationException;
import entities.AccountHeader;
import entities.Folder;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Tomas
 */
@Stateless
@LocalBean
public class NewFolderService implements InvokeActionInterface<NewFolderCrate> {
    @EJB
    private FolderService folderService;
    
    @PersistenceContext(unitName = "tCloudEE-ejbPU")
    private EntityManager em;
    
    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")

    @Override
    public void processAction(NewFolderCrate actionData, Long userId, AccountHeader accHeader) throws TCloudAplicationException {
        em.refresh(accHeader.getRootFolder());
        if(Utils.findFolder(accHeader.getRootFolder(), actionData.getPath()) != null){
            throw new TCloudAplicationException(100, actionData.getPath());
        }        
        
        Folder parentFolder = Utils.findParentFolder(accHeader.getRootFolder(), actionData.getPath());
        
        folderService.newFolder(userId, Utils.getNameFromPath(actionData.getPath()), parentFolder);
        
    }
}
